from django.shortcuts import render, redirect

from polls.models import Subject, Teacher


def index(request):
    """首页（获取所有学科）"""
    queryset = Subject.objects.all()
    context = {
        'subjects': queryset
    }
    return render(request, 'subjects.html', context)


def show_teachers(request):
    """显示指定学科的老师"""
    try:
        sno = request.GET['sno']
        subject = Subject.objects.get(no=sno)
        queryset = Teacher.objects.filter(subject__no=sno)
        context = {
            'subject': subject,
            'teachers': queryset
        }
        return render(request, 'teachers.html', context)
    except (KeyError, ValueError, Subject.DoesNotExist):
        return redirect('/')


def praise(request):
    pass
    # tno = request.GET.get('tno', '0')
    # sno = request.GET.get('sno', '0')
    # teacher = ...
    # teacher.good_count += 1
    # teacher.save()
    # return redirect(f'/teachers/?sno={sno}')


# def index(request: HttpRequest):
#     fruits = ['苹果', '香蕉', '菠萝', '草莓', '西瓜',
#               '榴莲', '火龙果', '猕猴桃', '山竹']
#     context = {
#         'fruits': sample(fruits, 3),
#         'greeting': '你好，世界'
#     }
#     return render(request, 'subjects.html', context)


# def index(request: HttpRequest):
#     fruits = ['苹果', '香蕉', '菠萝', '草莓', '西瓜',
#               '榴莲', '火龙果', '猕猴桃', '山竹']
#     content = StringIO()
#     content.write('<h2>今日推荐水果</h2>\r\n')
#     content.write('<hr>\r\n')
#     content.write('<ul>\r\n')
#     for fruit in sample(fruits, 3):
#         content.write(f'\t<li>{fruit}</li>\r\n')
#     content.write('</ul>\r\n')
#     return HttpResponse(content.getvalue())
